package com.ruoyi.collect.service.impl;

import com.ruoyi.collect.domain.CollectSite;
import com.ruoyi.collect.engine.client.MacCmsApiClient;
import com.ruoyi.collect.mapper.CollectSiteMapper;
import com.ruoyi.collect.service.ICollectSiteService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.movie.domain.MovieBasics;
import com.ruoyi.movie.mapper.CastMapper;
import com.ruoyi.movie.mapper.MovieBasicsMapper;
import com.ruoyi.movie.mapper.VideoResourceMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采集站点服务实现类
 *
 * @author ruoyi
 * @date 2025-11-07
 */
@Service
public class CollectSiteServiceImpl implements ICollectSiteService {

    private static final Logger log = LoggerFactory.getLogger(CollectSiteServiceImpl.class);

    @Autowired
    private CollectSiteMapper collectSiteMapper;

    @Autowired
    private MacCmsApiClient macCmsApiClient;

    @Autowired
    private MovieBasicsMapper movieBasicsMapper;

    @Autowired
    private CastMapper castMapper;

    @Autowired
    private VideoResourceMapper videoResourceMapper;

    /**
     * 查询采集站点
     *
     * @param siteId 站点ID
     * @return 采集站点
     */
    @Override
    public CollectSite selectCollectSiteById(Long siteId) {
        return collectSiteMapper.selectCollectSiteById(siteId);
    }

    /**
     * 查询采集站点列表
     *
     * @param collectSite 采集站点
     * @return 采集站点列表
     */
    @Override
    public List<CollectSite> selectCollectSiteList(CollectSite collectSite) {
        return collectSiteMapper.selectCollectSiteList(collectSite);
    }

    /**
     * 新增采集站点
     *
     * @param collectSite 采集站点
     * @return 结果
     */
    @Override
    public int insertCollectSite(CollectSite collectSite) {
        collectSite.setCreateTime(DateUtils.getNowDate());
        return collectSiteMapper.insertCollectSite(collectSite);
    }

    /**
     * 修改采集站点
     *
     * @param collectSite 采集站点
     * @return 结果
     */
    @Override
    public int updateCollectSite(CollectSite collectSite) {
        collectSite.setUpdateTime(DateUtils.getNowDate());
        return collectSiteMapper.updateCollectSite(collectSite);
    }

    /**
     * 批量删除采集站点
     *
     * @param siteIds 需要删除的站点ID
     * @return 结果
     */
    @Override
    public int deleteCollectSiteByIds(Long[] siteIds) {
        return collectSiteMapper.deleteCollectSiteByIds(siteIds);
    }

    /**
     * 删除采集站点
     *
     * @param siteId 站点ID
     * @return 结果
     */
    @Override
    public int deleteCollectSiteById(Long siteId) {
        return collectSiteMapper.deleteCollectSiteById(siteId);
    }

    /**
     * 测试站点连接
     *
     * @param siteId 站点ID
     * @return 如果连接成功返回true
     */
    @Override
    public boolean testSiteConnection(Long siteId) {
        try {
            CollectSite site = selectCollectSiteById(siteId);
            if (site == null) {
                log.error("站点不存在: {}", siteId);
                return false;
            }

            boolean result = macCmsApiClient.testConnection(site.getSiteUrl());

            // 更新最后测试时间
            site.setUpdateTime(DateUtils.getNowDate());
            updateCollectSite(site);

            return result;
        } catch (Exception e) {
            log.error("测试站点 {} 连接失败: {}", siteId, e.getMessage());
            return false;
        }
    }

    /**
     * 获取活动的采集站点
     *
     * @return 活动站点列表
     */
    @Override
    public List<CollectSite> selectActiveSites() {
        CollectSite query = new CollectSite();
        query.setStatus("0"); // 活动状态
        return selectCollectSiteList(query);
    }

    /**
     * 删除采集站点的所有数据
     *
     * @param siteId 站点ID
     * @return 删除统计信息
     */
    @Override
    @Transactional
    public Map<String, Object> deleteCollectedData(Long siteId) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);

        try {
            // 查询站点信息
            CollectSite site = selectCollectSiteById(siteId);
            if (site == null) {
                result.put("message", "站点不存在");
                return result;
            }

            String collectFrom = site.getSiteFlag();

            // 执行批量删除
            Map<String, Object> deleteStats = deleteDataByCollectFrom(collectFrom);

            result.put("success", true);
            result.put("message", "删除成功");
            result.putAll(deleteStats);

            log.info("成功删除站点 {} 的所有采集数据，共删除 {} 条影视记录",
                site.getSiteName(), deleteStats.get("movieCount"));

        } catch (Exception e) {
            log.error("删除站点 {} 数据失败: {}", siteId, e.getMessage(), e);
            result.put("message", "删除失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 按站点标识删除采集数据
     *
     * @param siteFlag 站点标识
     * @return 删除统计信息
     */
    @Override
    @Transactional
    public Map<String, Object> deleteCollectedDataBySiteFlag(String siteFlag) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);

        try {
            Map<String, Object> deleteStats = deleteDataByCollectFrom(siteFlag);

            result.put("success", true);
            result.put("message", "删除成功");
            result.putAll(deleteStats);

            log.info("成功删除采集来源 {} 的所有数据，共删除 {} 条影视记录",
                siteFlag, deleteStats.get("movieCount"));

        } catch (Exception e) {
            log.error("删除采集来源 {} 数据失败: {}", siteFlag, e.getMessage(), e);
            result.put("message", "删除失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 获取站点采集数据统计
     *
     * @param siteId 站点ID
     * @return 数据统计信息
     */
    @Override
    public Map<String, Object> getCollectedDataStats(Long siteId) {
        Map<String, Object> stats = new HashMap<>();

        try {
            CollectSite site = selectCollectSiteById(siteId);
            if (site == null) {
                stats.put("movieCount", 0);
                return stats;
            }

            // 查询该站点采集的影视数量
            MovieBasics query = new MovieBasics();
            query.setCollectFrom(site.getSiteFlag());
            List<MovieBasics> movies = movieBasicsMapper.selectMovieBasicsList(query);

            stats.put("movieCount", movies.size());
            stats.put("siteFlag", site.getSiteFlag());
            stats.put("siteName", site.getSiteName());

        } catch (Exception e) {
            log.error("获取站点 {} 数据统计失败: {}", siteId, e.getMessage());
            stats.put("movieCount", 0);
        }

        return stats;
    }

    /**
     * 按采集来源删除数据（私有方法）
     *
     * @param collectFrom 采集来源标识
     * @return 删除统计信息
     */
    private Map<String, Object> deleteDataByCollectFrom(String collectFrom) {
        Map<String, Object> stats = new HashMap<>();

        int totalMovieCount = 0;
        int totalCastCount = 0;
        int totalResourceCount = 0;

        // 1. 查询所有需要删除的影视ID
        MovieBasics query = new MovieBasics();
        query.setCollectFrom(collectFrom);
        List<MovieBasics> movies = movieBasicsMapper.selectMovieBasicsList(query);

        if (movies.isEmpty()) {
            stats.put("movieCount", 0);
            stats.put("castCount", 0);
            stats.put("resourceCount", 0);
            return stats;
        }

        // 2. 批量删除关联数据（每100条一批）
        int batchSize = 100;
        for (int i = 0; i < movies.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, movies.size());
            List<MovieBasics> batch = movies.subList(i, endIndex);

            List<Long> movieIds = new ArrayList<>();
            for (MovieBasics movie : batch) {
                if (movie.getMovieBasicsId() != null) {
                    movieIds.add(movie.getMovieBasicsId().longValue());
                }
            }

            // 删除演职人员关联
            int castCount = castMapper.deleteCastByMovieIds(movieIds);
            totalCastCount += castCount;

            // 删除视频资源
            int resourceCount = videoResourceMapper.deleteVideoResourceByMovieIds(movieIds);
            totalResourceCount += resourceCount;

            log.debug("批次 {}-{}: 删除 {} 个演员关联，{} 个视频资源",
                i, endIndex, castCount, resourceCount);
        }

        // 3. 删除影视基础数据
        int movieCount = movieBasicsMapper.deleteMovieBasicsByCollectFrom(collectFrom);
        totalMovieCount = movieCount;

        stats.put("movieCount", totalMovieCount);
        stats.put("castCount", totalCastCount);
        stats.put("resourceCount", totalResourceCount);

        return stats;
    }
}
